package com.greateamd.timetableasy.client.widgets;

import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.ToggleButton;

public class LabelizableListBox extends HorizontalPanel {
	
	private final ListBox list = new ListBox(false);
	private final TextBox customLabelTb = new TextBox(); 
	private final ToggleButton changeCustom = new ToggleButton("Custom","Choice");
	
	private String value = "";
	
	public LabelizableListBox(boolean multi) {
		setHandler();
		list.setMultipleSelect(multi);
		customLabelTb.setVisible(false);
		add(list);
		add(customLabelTb);
		add(changeCustom);
	}
	
	private void setHandler() {
		list.addChangeHandler(new ChangeHandler() {
			@Override
			public void onChange(ChangeEvent arg0) {
				value = list.getSelectedValue();				
			}
		});
		customLabelTb.addBlurHandler(new BlurHandler() {
			@Override
			public void onBlur(BlurEvent arg0) {
				value = customLabelTb.getText();
			}
		});
		changeCustom.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent arg0) {
				setCustomBoxVisible(!customLabelTb.isVisible());
			}
		});
	}

	protected void setCustomBoxVisible(boolean visible) {
		list.setVisible(!visible);
		customLabelTb.setVisible(visible);
		changeCustom.setDown(visible);
		if(visible)
			value = customLabelTb.getText();
		else
			value = list.getSelectedValue();
	}

	public void addValue(String value){
		list.addItemIfNotPresent(value);
	}

	public void setValue(String value) {
		customLabelTb.setText(value);
		setCustomBoxVisible(true);
	}
	
	public void setEnabled(boolean enabled){
		changeCustom.setEnabled(enabled);
		customLabelTb.setEnabled(enabled);
		list.setEnabled(enabled);
	}
	
	public String getValue() {
		if(customLabelTb.isVisible())
			return customLabelTb.getText();
		else
			return value;
	}
	
	@Override
	public void clear() {
		list.clear();
	}
	
	public void setReadOnly(final boolean read){
		setEnabled(!read);
		changeCustom.setVisible(!read);
	}

	public int getSelectedIndex() {
		return list.getSelectedIndex();
	}

	public void setSelectedIndex(int selectedIndex) {
		list.setSelectedIndex(selectedIndex);
	}
	
	public void addItem(String value){
		list.addItem(value);
	}
	
	public void addBlurHandler(BlurHandler handler){
		list.addBlurHandler(handler);
		customLabelTb.addBlurHandler(handler);
	}
}
